import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Descriptions,
  Tag,
  Spin,
  Typography,
  Space,
  Button,
  Empty,
  message,
} from 'antd';
import { ArrowLeftOutlined, FileTextOutlined } from '@ant-design/icons';
import {
  getRecordDetail,
  getRecordLatestAssessment,
  type RecordDetail,
  type AssessmentDetail,
} from '@/api';

const { Title, Text } = Typography;

const Assessment = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [record, setRecord] = useState<RecordDetail | null>(null);
  const [assessment, setAssessment] = useState<AssessmentDetail | null>(null);

  useEffect(() => {
    if (id) {
      loadData();
    }
  }, [id]);

  const loadData = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const [recordRes, assessmentRes] = await Promise.all([
        getRecordDetail(id),
        getRecordLatestAssessment(id).catch(() => null),
      ]);
      setRecord(recordRes.data.data);
      setAssessment(assessmentRes?.data?.data || null);
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!record) {
    return <Empty description="病历不存在" />;
  }

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>
          返回
        </Button>
        {assessment && (
          <Button
            type="primary"
            icon={<FileTextOutlined />}
            onClick={() => navigate(`/report/${id}`)}
          >
            查看完整报告
          </Button>
        )}
      </Space>

      <Title level={2}>病历详情</Title>

      <Card title="患者信息" style={{ marginTop: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="姓名">{record.patient_name}</Descriptions.Item>
          <Descriptions.Item label="性别">{record.patient_gender || '-'}</Descriptions.Item>
          <Descriptions.Item label="年龄">
            {record.patient_age !== null ? `${record.patient_age}岁` : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="就诊卡号">
            {record.patient_card_number || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="科室">{record.department || '-'}</Descriptions.Item>
          <Descriptions.Item label="就诊日期">
            {record.visit_date ? new Date(record.visit_date).toLocaleString('zh-CN') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="医生签名">{record.doctor_name || '-'}</Descriptions.Item>
        </Descriptions>
      </Card>

      <Card title="病情信息" style={{ marginTop: 16 }}>
        <Descriptions column={1} bordered>
          <Descriptions.Item label="主诉">{record.chief_complaint || '-'}</Descriptions.Item>
          <Descriptions.Item label="现病史">
            {record.present_illness || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="过敏史">
            {record.allergy_history || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="既往史">{record.past_history || '-'}</Descriptions.Item>
          <Descriptions.Item label="体格检查">
            {record.physical_exam || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="辅助检查">
            {record.auxiliary_exam || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="诊断">
            {record.diagnosis && record.diagnosis.length > 0
              ? record.diagnosis.map((d, i) => <div key={i}>{d}</div>)
              : '-'}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      {record.medications && record.medications.length > 0 && (
        <Card title="用药信息" style={{ marginTop: 16 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            {record.medications.map((med, index) => (
              <Card key={med.id} type="inner" size="small" title={`药物 ${index + 1}`}>
                <Descriptions column={2} size="small">
                  <Descriptions.Item label="药品名称">{med.medication_name}</Descriptions.Item>
                  <Descriptions.Item label="规格">{med.specification || '-'}</Descriptions.Item>
                  <Descriptions.Item label="用法">{med.route || '-'}</Descriptions.Item>
                  <Descriptions.Item label="频次">{med.frequency || '-'}</Descriptions.Item>
                  <Descriptions.Item label="剂量">
                    {med.dosage_value && med.dosage_unit
                      ? `${med.dosage_value}${med.dosage_unit}`
                      : '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="用药天数">
                    {med.duration ? `${med.duration}天` : '-'}
                  </Descriptions.Item>
                </Descriptions>
              </Card>
            ))}
          </Space>
        </Card>
      )}

      {record.instructions && record.instructions.length > 0 && (
        <Card title="医嘱信息" style={{ marginTop: 16 }}>
          <ul>
            {record.instructions.map((inst, index) => (
              <li key={inst.id}>{inst.instruction_text}</li>
            ))}
          </ul>
        </Card>
      )}

      {assessment && (
        <Card title="评估结果" style={{ marginTop: 16 }}>
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <div>
              <Title level={3} style={{ marginBottom: 16 }}>
                综合评分：
                <Text
                  strong
                  style={{
                    fontSize: 48,
                    marginLeft: 16,
                    color: getScoreColor(assessment.overall_score),
                  }}
                >
                  {assessment.overall_score}
                </Text>
                <Text type="secondary" style={{ fontSize: 20, marginLeft: 8 }}>
                  / 100
                </Text>
              </Title>
            </div>

            <Descriptions column={4} bordered>
              <Descriptions.Item label="完整性">
                <Tag color={getScoreTagColor(assessment.completeness_score)}>
                  {assessment.completeness_score}分
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="规范性">
                <Tag color={getScoreTagColor(assessment.standardization_score)}>
                  {assessment.standardization_score}分
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="一致性">
                <Tag color={getScoreTagColor(assessment.consistency_score)}>
                  {assessment.consistency_score}分
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="准确性">
                <Tag color={getScoreTagColor(assessment.accuracy_score)}>
                  {assessment.accuracy_score}分
                </Tag>
              </Descriptions.Item>
            </Descriptions>

            {assessment.summary && (
              <Card type="inner" title="评估总结">
                <Text>{assessment.summary}</Text>
              </Card>
            )}

            {assessment.suggestions && assessment.suggestions.length > 0 && (
              <Card type="inner" title="改进建议">
                <ul>
                  {assessment.suggestions.map((suggestion, index) => (
                    <li key={index}>{suggestion}</li>
                  ))}
                </ul>
              </Card>
            )}
          </Space>
        </Card>
      )}
    </div>
  );
};

const getScoreColor = (score: number): string => {
  if (score >= 90) return '#52c41a';
  if (score >= 80) return '#1890ff';
  if (score >= 70) return '#faad14';
  if (score >= 60) return '#fa8c16';
  return '#f5222d';
};

const getScoreTagColor = (score: number): string => {
  if (score >= 90) return 'success';
  if (score >= 80) return 'processing';
  if (score >= 70) return 'warning';
  return 'error';
};

export default Assessment;
